﻿using System.Text;
using Yz.Base;
using Yz.Core.Extensions;
using Yz.Core.Tools;
using Yz.FileService.Tools;

namespace Yz.FileService.Middlewares
{
    public class PreviewMiddleware : BaseUploadMiddleware, IMiddleware
    {
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            context.Response.ContentType = "application/json; charset=utf-8";
            #region 跨域上传
            if (context.Request.Method.Equals(HttpMethods.Options, StringComparison.OrdinalIgnoreCase))
            {
                base.AddHttpOptionHeader(context);
            }
            #endregion

            #region 后台post上传
            else if (context.Request.Method.Equals(HttpMethods.Get, StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    #region 验证token
                    var validRes = await ValidateTokenAsync(context);
                    //if (!validRes.Item1.IsEmpty())
                    //{
                    //    await context.Response.WriteAsync(new VmUpFileBase()
                    //    {
                    //        Msg = validRes.Item1
                    //    }.ToJsonStr());
                    //    return;
                    //}
                    string appId = validRes.Item2;
                    #endregion

                    string fileId = context.Request.Query["id"];
                    if (string.IsNullOrEmpty(fileId))
                    {
                        await context.Response.WriteAsync(new VmUpFileBase()
                        {
                            Msg = "您要预览的文件不存在！"
                        }.ToJsonStr());
                        return;
                    }
                    string flPath = fileId.ToDesDecrypt();
                    string filePhysicalPath = (_uploadConfig.PhysicalPath + flPath).ToLower();
                    string ext = Path.GetExtension(filePhysicalPath);
                    if (appId.IsEmpty() || !flPath.StartsWith("/" + appId + "/"))
                    {
                        await context.Response.WriteAsync(new VmUpFileBase()
                        {
                            Msg = "您没有权限访问此文件！"
                        }.ToJsonStr());
                        return;
                    }
                    if (!FileTypeList.DocPreviewList.Contains(ext))
                    {
                        await context.Response.WriteAsync(new VmUpFileBase()
                        {
                            Msg = "此文件不支持预览！"
                        }.ToJsonStr());
                        return;
                    }
                    if (!File.Exists(filePhysicalPath))
                    {
                        await context.Response.WriteAsync(new VmUpFileBase()
                        {
                            Msg = "您要预览的文件不存在！"
                        }.ToJsonStr());
                        return;
                    }
                    context.Response.ContentType = "text/html";
                    if (ext == ".pdf")//pdf文件预览
                    {
                        string htmlPath = filePhysicalPath.Replace(".pdf", ".html");
                        string htmlContent = "";
                        //html存在
                        if (File.Exists(htmlPath))
                        {
                            htmlContent = File.ReadAllText(htmlPath, Encoding.UTF8);
                        }
                        else
                        {
                            string filePath = _uploadConfig.VirtualPath + flPath;
                            htmlContent = File.ReadAllText(_uploadConfig.PhysicalPath + "/html/pdf.html", Encoding.UTF8).Replace("$fileUrl$", filePath);
                            using (var fileStream = new FileStream(htmlPath, FileMode.Create))
                            {
                                byte[] data = Encoding.UTF8.GetBytes(htmlContent);
                                fileStream.Write(data, 0, data.Length);
                            }
                        }
                        await context.Response.WriteAsync(htmlContent, Encoding.UTF8);
                    }
                    else if (ext == ".docx")
                    {
                        string htmlPath = filePhysicalPath.Replace(".docx", ".html");
                        string htmlContent = "";
                        //html存在
                        if (File.Exists(htmlPath))
                        {
                            htmlContent = File.ReadAllText(htmlPath, Encoding.UTF8);
                        }
                        else
                        {
                            htmlContent = YzWord.ToHtml(filePhysicalPath);
                            using (var fileStream = new FileStream(htmlPath, FileMode.Create))
                            {
                                byte[] data = Encoding.UTF8.GetBytes(htmlContent);
                                fileStream.Write(data, 0, data.Length);
                            }
                        }
                        await context.Response.WriteAsync(htmlContent, Encoding.UTF8);
                    }
                    else if (ext == ".xlsx" || ext == ".xls")
                    {
                        string htmlPath = filePhysicalPath.Replace(".xlsx", ".html").Replace(".xls", ".html");
                        string htmlContent = "";
                        //html存在
                        if (File.Exists(htmlPath))
                        {
                            htmlContent = File.ReadAllText(htmlPath, Encoding.UTF8);
                        }
                        else
                        {
                            htmlContent = YzExcel.ToHtml(filePhysicalPath);
                            using (var fileStream = new FileStream(htmlPath, FileMode.Create))
                            {
                                byte[] data = Encoding.UTF8.GetBytes(htmlContent);
                                fileStream.Write(data, 0, data.Length);
                            }
                        }
                        await context.Response.WriteAsync(htmlContent, Encoding.UTF8);
                    }
                    else
                    {
                        context.Response.ContentType = "application/json; charset=utf-8";
                        await context.Response.WriteAsync(new VmUpFileBase()
                        {
                            Msg = "此文件不支持预览！"
                        }.ToJsonStr());
                    }
                    return;
                }
                catch (Exception ex)
                {
                    context.Response.ContentType = "application/json; charset=utf-8";
                    YzNLog.Error(ex);
                    await context.Response.WriteAsync(new VmUpFileBase()
                    {
                        Msg = "此文件不支持预览！"
                    }.ToJsonStr());
                }
            }
            #endregion

            #region 非法上传
            else
            {
                await base.AddHttpNotAllowedAsync(context);
            }
            #endregion
        }
    }
}
